package controller;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description: 实现博客编辑页的功能
 */
@WebServlet("/blogEdit")
public class BlogEditServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf8");
        // 获取博客标题和博客正文
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || "".equals(title) || content == null || "".equals(content)) {
            resp.getWriter().write("博客提交失败,标题或正文内容缺失!");
            return;
        }
        // 通过会话获取博客的用户id
        HttpSession session = req.getSession();
        if(session == null) {
            resp.getWriter().write("用户未登录，会话不存在!");
            resp.sendRedirect("blog_login.html");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.getWriter().write("用户未登录，会话信息不存在!");
            resp.sendRedirect("blog_login.html");
            return;
        }
        // 实例化一个博客对象
        Blog blog = new Blog();
        //    blogId和postTime都不需要手动指定，插入数据库时会自动生成
        blog.setUserId(user.getUserId());
        blog.setTitle(title);
        blog.setContent(content);
        // 添加博客
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        // 重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
